package org.nerve.okhttp3.cookie;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.annotation.JSONField;
import okhttp3.Cookie;

import java.io.Serializable;
import java.util.*;
import java.util.concurrent.CopyOnWriteArrayList;

/**
 * org.nerve.okhttp3.cookie
 * Created by zengxm on 2016/7/25.
 */
public class HostCookie implements Serializable{
	private String host;
	private List<Map<String,String>> cookies=new CopyOnWriteArrayList<>();

	public HostCookie(){}

	public HostCookie(String host){
		this.host = host;
	}

	/**
	 * 获取okHttp对应的cookie
	 * @return
	 */
	@JSONField(serialize = false)
	public List<Cookie> getOkHttpCookies(){
		if(cookies == null)
			return Collections.emptyList();

		List<Cookie> cookieList=new ArrayList<>();
		cookies.forEach(c->{
			Cookie.Builder builder=new Cookie.Builder();
			builder.domain(c.get("domain"))
					.value(c.get("value"))
					.path(c.get("path"))
					.name(c.get("name"))
					;

			cookieList.add(builder.build());
		});

		return cookieList;
	}

	@JSONField(ordinal = 0)
	public String getHost() {
		return host;
	}

	public HostCookie setHost(String host) {
		this.host = host;
		return this;
	}

	@JSONField(ordinal = 1)
	public List<Map<String, String>> getCookies() {
		return cookies;
	}

	public HostCookie setCookies(List<Map<String, String>> cookies) {
		this.cookies = cookies;
		return this;
	}

	/**
	 * 添加一个Cookie
	 * @param cookie
	 * @return
	 */
	public HostCookie add(Cookie cookie){
		if(cookie!=null){
			Map<String,String> map=new HashMap<>();
			map.put("name", cookie.name());
			map.put("domain", cookie.domain());
			map.put("path", cookie.path());
			map.put("value", cookie.value());

			cookies.add(map);
		}
		return this;
	}
}
